package com.lv.service.adapter;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.material.imageview.ShapeableImageView;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lv.service.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者： ygx
 * 创建日期：2023/6/6 10:32 AM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：通用图片选择  布局需要 iv_img ll_del 有添加按钮，可以删除
 */
public class GridImageAdapter extends
        RecyclerView.Adapter<GridImageAdapter.ViewHolder> {
    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_PICTURE = 2;
    private LayoutInflater mInflater;
    private int mLayout;
    private List<LocalMedia> list = new ArrayList<>();
    private int selectMax = 9;

    /**
     * 删除
     */
    public void delete(int position) {
        try {

            if (position != RecyclerView.NO_POSITION && list.size() > position) {
                list.remove(position);
                notifyItemRemoved(position);
                notifyItemRangeChanged(position, list.size());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 点击添加图片跳转
     */
    private onAddPicClickListener mOnAddPicClickListener;

    public interface onAddPicClickListener {
        void onAddPicClick();
    }

    public GridImageAdapter(Context context, @LayoutRes int layout, onAddPicClickListener mOnAddPicClickListener) {
        mInflater = LayoutInflater.from(context);
        this.mLayout=layout;
        this.mOnAddPicClickListener = mOnAddPicClickListener;
    }

    public void setSelectMax(int selectMax) {
        this.selectMax = selectMax;
    }

    public int getSelectMax() {
        return selectMax;
    }

    public void remove(int position) {
        if (position < list.size()) {
            list.remove(position);
        }
    }

    public void setList(List<LocalMedia> list) {
        this.list = list;
        notifyDataSetChanged();
    }

    public List<LocalMedia> getData() {
        return list;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        ShapeableImageView mImg;
        LinearLayout llDel;
//        TextView tvDuration;

        public ViewHolder(View view) {
            super(view);
            mImg = view.findViewById(R.id.iv_img);
            llDel = view.findViewById(R.id.ll_del);
//            tvDuration = view.findViewById(R.id.tv_duration);
        }
    }

    @Override
    public int getItemCount() {
        if (list.size() < selectMax) {
            return list.size() + 1;
        } else {
            return list.size();
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (isShowAddItem(position)) {
            return TYPE_CAMERA;
        } else {
            return TYPE_PICTURE;
        }
    }

    /**
     * 创建ViewHolder
     */
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = mInflater.inflate(mLayout,
                viewGroup, false);
        final ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    private boolean isShowAddItem(int position) {
        int size = list.size();
        return position == size;
    }

    /**
     * 设置值
     */
    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
        //少于8张，显示继续添加的图标
        if (getItemViewType(position) == TYPE_CAMERA) {
            viewHolder.mImg.setImageResource(com.lv.common.R.drawable.ic_add_image);
            viewHolder.mImg.setOnClickListener(v -> {
                if (mOnAddPicClickListener != null) {
                    mOnAddPicClickListener.onAddPicClick();
                }
            });
            viewHolder.llDel.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.llDel.setVisibility(View.VISIBLE);
            viewHolder.llDel.setOnClickListener(view -> {
                int index = viewHolder.getAbsoluteAdapterPosition();
                // 这里有时会返回-1造成数据下标越界,具体可参考getAdapterPosition()源码，
                // 通过源码分析应该是bindViewHolder()暂未绘制完成导致，知道原因的也可联系我~感谢
                if (index != RecyclerView.NO_POSITION && list.size() > index) {
                    list.remove(index);
                    notifyItemRemoved(index);
                    notifyItemRangeChanged(index, list.size());
                    if (list.size() == 0 && onItemClearClickListener != null) {
                        onItemClearClickListener.onItemClearClick(position);
                    }
                }
            });
            LocalMedia media = list.get(position);
//            int chooseModel = media.getChooseModel();
            String path = media.getAvailablePath();
            if (TextUtils.isEmpty(path)) {
                path = media.getCompressPath();
            }
//            String path;
//            path = media.getCompressPath();
            Glide.with(viewHolder.itemView.getContext())
                    .load(PictureMimeType.isContent(path) && !media.isCut() && !media.isCompressed() ? Uri.parse(path)
                            : path)
                    .centerCrop()
                    .placeholder(com.lv.common.R.color.color_f8f8f8)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(viewHolder.mImg);
//            Glide.with(viewHolder.itemView.getContext())
//                    .load(path)
////                    .apply(options)
//                    .into(viewHolder.mImg);
//            }
            //itemView 的点击事件
            if (mItemClickListener != null) {
                String finalPath = path;
                viewHolder.itemView.setOnClickListener(v -> {
                    int adapterPosition = viewHolder.getAdapterPosition();
                    mItemClickListener.onItemClick(adapterPosition, v, finalPath);
                });
            }

        }
    }

    protected OnItemClickListener mItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(int position, View v, String path);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mItemClickListener = listener;
    }

    protected OnItemClearClickListener onItemClearClickListener;

    public interface OnItemClearClickListener {
        void onItemClearClick(int position);
    }

    public void setOnItemClearClickListener(OnItemClearClickListener onItemClearClickListener) {
        this.onItemClearClickListener = onItemClearClickListener;
    }
}
